package com.example.springboot.config.redis;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.listener.PatternTopic;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;

/**
 * redis键过期监听
 * 用于订单过期，key过期只能通知一次，无论消费者是否消费
 * 使用前在redis.conf中配置  notify-keyspace-events "Ex"
 *
 * @Author:ChenZhangKun
 * @Date: 2023/10/14 17:51
 */
@Configuration
public class ListenKeyExpire {

    @Autowired
    private RedisConnectionFactory redisConnectionFactory;

    @Bean
    public RedisMessageListenerContainer redisMessageListenerContainer() {
        RedisMessageListenerContainer container = new RedisMessageListenerContainer();
        container.setConnectionFactory(redisConnectionFactory);
        container.addMessageListener((message, bytes) -> {
            String expireKey = message.toString();
            if (expireKey.startsWith("order:")) {
                //
                System.out.println("【处理过期的订单】：");
            }
        }, new PatternTopic("__keyevent@*__:expired"));
        return container;
    }
}
